package api;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.MD5;
import cn.hutool.json.JSONUtil;
import common.ApplicationVariable;
import lombok.SneakyThrows;
import model.ResultData;
import model.UserInfo;
import util.DBUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

/**
 * 登录
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @SneakyThrows
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType(ApplicationVariable.RESPONSE_CONTENT_TYPE);
        int state=-1;
        String data="";
        String msg="未知错误！";
        String username=req.getParameter("username");
        String password=req.getParameter("password");
        String isadmin=req.getParameter("isadmin");
        if(!StrUtil.isBlank(username)&&!StrUtil.isBlank(password)){
            Connection connection= DBUtil.getConnection();
            String sql="select * from userinfo where username=?and password=?";
            if(!StrUtil.isBlank(isadmin)){//超管登录
                sql+="and isadmin=1";
            }
            PreparedStatement statement= connection.prepareStatement(sql);
            statement.setString(1,username);
            statement.setString(2, MD5.create().digestHex(password)); //数据库密码加密
            ResultSet resultSet=statement.executeQuery();
            if(resultSet.next()){
                //用户名密码正确
                state=200;
                data=username;
                msg="";
                HttpSession session=req.getSession(true);
                UserInfo userInfo=new UserInfo();
                userInfo.setUid(resultSet.getInt("uid"));
                userInfo.setUsername(resultSet.getString("username"));
                if (session!=null){
                session.setAttribute(ApplicationVariable.SESSION_USER_KEY,userInfo);
                }
            }else {
                msg="用户名或密码错误！";
            }
        }else{
            msg="非法参数";
        }

        //3.结果返回给前端
        ResultData resultData= new ResultData();
        resultData.setState(state);
        resultData.setData(data);
        resultData.setMsg(msg);
        resp.getWriter().println(JSONUtil.toJsonStr(resultData));
    }
}
